package com.spark.gaea.security.matcher;

import com.spark.gaea.security.backend.SecurityBackend;
import com.spark.gaea.security.domain.SecurityUser;
import com.spark.gaea.security.eis.PasswordEncoder;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;

public class GaeaCredentialsMatcher extends SimpleCredentialsMatcher {
	@Autowired
	private SecurityBackend securityBackend;

	@Override
	public boolean doCredentialsMatch(final AuthenticationToken authcToken, final AuthenticationInfo info) {
		final UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		final String password = String.valueOf(token.getPassword());
		if ("SECRET-KEY-SSO".equals(password)) {
			return true;
		}
		final String username = token.getUsername();
		final SecurityUser user = this.securityBackend.getUser(username);
		if (user == null) {
			return false;
		}
		final Object tokenCredentials = this.encrypt(String.valueOf(token.getPassword()), user.getSalt());
		System.out.println(tokenCredentials.toString());
		final Object accountCredentials = this.getCredentials(info);
		return this.equals(tokenCredentials, accountCredentials);
	}

	private String encrypt(final String data, final String salt) {
		return PasswordEncoder.encodePassword(data, salt);
	}
}
